#include	"World.h"

World::World()
{
	for( int i = 0; i < CONF::GRAIDNUM; i ++ )
	{
		for( int j = 0; j < CONF::GRAIDNUM; j ++ )
		{
			(mGrid[i][j]).curr = 0;
			(mGrid[i][j]).next = 0;
		}
	}
}
World::~World()
{

}

int World::GetNeiNum( int x, int y )
{
	int num = 0;

	for( int i = -1; i <= 1; i ++ )
	{
		for( int j = -1; j <= 1; j ++ )
		{
			if( i == 0 && j == 0 )
			{
				continue;
			}

			int xPos = x + i; 
			int yPos = y + j;

			if( Legal( xPos, yPos ) )
			{
				if( (mGrid[xPos][yPos]).curr == 1 )
				{
					num ++;
				}
			}
		}
	}

	return num;
}

void World::SetNew( int x, int y )
{
	(mGrid[x][y]).next = 1;
}

void World::SetLive( int x, int y )
{
	(mGrid[x][y]).next = (mGrid[x][y]).curr;
}

void World::SetDead( int x, int y )
{
	(mGrid[x][y]).next = 0;
}

bool World::Legal( int x, int y)
{
	if( x >= 0 && x < CONF::GRAIDNUM
	   && y >= 0 && y < CONF::GRAIDNUM )
	{
		return true;
	}
	else
	{
		return false;
	}
}

void World::Update()
{
	for( int i = 0; i < CONF::GRAIDNUM; i ++ )
	{
		for( int j = 0; j < CONF::GRAIDNUM; j ++ )
		{
			(mGrid[i][j]).next = 0;
		}
	}

	for( int i = 0; i < CONF::GRAIDNUM; i ++ )
	{
		for( int j = 0; j < CONF::GRAIDNUM; j ++ )
		{
			int neiNum = GetNeiNum(i,j);

			if( neiNum == 3 )
			{
				SetNew( i, j );	
			}		
			else if( neiNum == 2 )
			{
				SetLive( i, j );	
			}
			else
			{
				SetDead( i, j );
			}
		}
	}

	for( int i = 0; i < CONF::GRAIDNUM; i ++ )
	{
		for( int j = 0; j < CONF::GRAIDNUM; j ++ )
		{
			if( (mGrid[i][j]).next == 1 )
			{
				(mGrid[i][j]).curr = 1;
			}
			else if( (mGrid[i][j]).next == 0 )
			{
				(mGrid[i][j]).curr = 0;
			}

			(mGrid[i][j]).next = 0;
		}
	}
}
